<!DOCTYPE html>
<html lang="zh-CN">
<!--浏览器搞笑标题-->
<script type="text/javascript" src="/js/FunnyTitle.js"></script>






<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/binblog/img/binblog.ico">
  <link rel="icon" type="image/png" href="/binblog/img/binblog.ico">
  <meta name="viewport"
        content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="description" content="">
  <meta name="author" content="leo-bin">
  <meta name="keywords" content="">
  <title>设计模式之代理模式 - 阿斌的个人博客</title>

  <link  rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.staticfile.org/github-markdown-css/4.0.0/github-markdown.min.css" />
  <link  rel="stylesheet" href="/binblog/lib/hint/hint.min.css" />

  
    <link  rel="stylesheet" href="https://cdn.staticfile.org/highlight.js/10.0.0/styles/dracula.min.css" />
  

  


<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_yg9cfy8wd6.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_pjno9b9zyxs.css">


<link  rel="stylesheet" href="/binblog/css/main.css" />

<!-- 自定义样式保持在最底部 -->


<meta name="generator" content="Hexo 4.2.1"></head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand"
       href="/binblog/">&nbsp;<strong>Abin的Blog</strong>&nbsp;</a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/binblog/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/binblog/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/binblog/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/binblog/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/binblog/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" data-toggle="modal" data-target="#modalSearch">&nbsp;&nbsp;<i
                class="iconfont icon-search"></i>&nbsp;&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="view intro-2" id="background" parallax=true
         style="background: url('/binblog/img/6.webp') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="container text-center white-text fadeInUp">
            <span class="h2" id="subtitle">
              
            </span>

            
              
  <div class="mt-3 post-meta">
    <i class="iconfont icon-date-fill" aria-hidden="true"></i>
    <time datetime="2020-05-31 22:11">
      2020年5月31日 晚上
    </time>
  </div>


<div class="mt-1">
  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      3.8k 字
    </span>
  

  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      47
       分钟
    </span>
  

  
  
    
      <!-- LeanCloud 统计文章PV -->
      <span id="leancloud-post-views-container" class="post-meta" style="display: none">
        <i class="iconfont icon-eye" aria-hidden="true"></i>
        <span id="leancloud-post-views"></span> 次
      </span>
    
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid">
  <div class="row">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-md">
      <div class="container nopadding-md" id="board-ctn">
        <div class="py-5" id="board">
          <div class="post-content mx-auto" id="post">
            
              <p class="note note-info">
                
                  本文最后更新于：2020年7月19日 凌晨
                
              </p>
            
            <article class="markdown-body">
              <h1 id="设计模式之代理模式"><a href="#设计模式之代理模式" class="headerlink" title="设计模式之代理模式"></a>设计模式之代理模式</h1><h2 id="前话"><a href="#前话" class="headerlink" title="前话"></a>前话</h2><p><strong>ok</strong>，上次咱们说了<strong>单例模式</strong>，今天我们来说一说<strong>代理模式</strong>。</p>
<p>正好复习到Spring和MyBatis了，发现现在但凡是任何一个主流框架的底层，或多或少都用到了代理模式。</p>
<p>比如Spring中的<code>AOP</code>，MyBatis中的<code>Mapper.xml</code>文件和<code>Mapper.java</code>类的映射实现。</p>
<p>看得出来，代理模式的重要性，但是同时，代理模式也是<strong><code>Java</code></strong>中最难以理解的技术之一。</p>
<p>记得刚开始学Java的时候，这块地方根本就没弄懂，然后后面需要准备春招的时候才看了下网上的总结。</p>
<p><strong>说实话，挺难理解的（太菜了亚）。</strong></p>
<p>但到了后面把Java一些其他特性，诸如<strong>继承，多态，反射，JVM</strong>等复习了一遍之后，这才对代理模式有了新的认识。</p>
<h2 id="说明"><a href="#说明" class="headerlink" title="说明"></a>说明</h2><p>首先，代理模式是<strong>设计模式</strong>的一种，通常我们说的代理模式分为<strong>两种类型</strong>：</p>
<p><strong><code>1.静态代理</code></strong>。</p>
<p><strong><code>2.动态代理</code></strong>。</p>
<p><br></p>
<h3 id="1）为什么会有代理模式的诞生呢？"><a href="#1）为什么会有代理模式的诞生呢？" class="headerlink" title="1）为什么会有代理模式的诞生呢？"></a>1）为什么会有代理模式的诞生呢？</h3><p><strong>我们先假设一个场景：</strong></p>
<p>现在有一个业务类叫做<strong>打印业务</strong>，里面有一个打印方法。</p>
<p>方法很简单，就是打印传过来的字符串就行。</p>
<p><br></p>
<p><strong>打印类如下：</strong></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PrintName</span></span>&#123;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">print</span><span class="hljs-params">(String name)</span> </span>&#123;
        System.out.println(<span class="hljs-string">"name="</span> + name);
    &#125;
&#125;</code></pre></div>
<p><br></p>
<p>现在有一个新的要求。需要在打印的时候，额外做一些其他事情，比如说调用其他接口的方法。</p>
<p>（这里为了图简单所以没有设计比较复杂的情况了）</p>
<p>一般我们会怎么做？直接加呗，不就是一个new的事情吗，多大的事😊</p>
<p><strong>像这样：</strong></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">print</span><span class="hljs-params">(String name)</span> </span>&#123;
    OtherClass other=<span class="hljs-keyword">new</span> OtherClass();
    other.action();
    System.out.println(<span class="hljs-string">"name="</span> + name);
&#125;</code></pre></div>
<p><br></p>
<p>ok,没问题，这样做确实可以。</p>
<p>但是如果你现在有10，100个这样的打印业务都需要调用下这个其他接口的方法呢？</p>
<p>还是<strong><code>All In One</code></strong>？一把梭？</p>
<p>不仅如此，如果这个其他接口改名字了呢？你也要跟着改100次吗？</p>
<p>很显然，在大型的软件开发场景中，这样做是不明确的！</p>
<p>这个也叫作模块之间的高耦合问题！</p>
<p>本来两个业务之间没有什么联系的，但是就是这种代码将两者紧密联系在一起了！</p>
<p>要死一起死？日后怕是会出大问题！</p>
<p>所以我们讲究的是：<strong><code>高内聚！低耦合！</code></strong></p>
<p>什么？不明白？</p>
<p>ok，说白了，就是如何在<strong>不污染一个业务类的代码的前提下，额外的多做一些事情</strong>！</p>
<p>怎么实现？我们可以看看现在的明星和经纪人（或者助理）。</p>
<p>明星主要干嘛？<strong>唱歌？跳舞？演习？演唱会？</strong></p>
<p>那谁来收钱？谁来联系唱片公司？谁来宣传？谁来负责明星的服装，摄影，化妆？</p>
<p>难道让明星一个人都做了？这很明显是不现实的！</p>
<p>所以后面就有了经纪人，助理。让他们来做这些事情！明星就做自己的本职工作就行！</p>
<p><strong>这里我们同样可以将代理当成经纪人或者助理！</strong></p>
<p><br></p>
<p><strong>ok，人找到了，但是现在还有一个问题！</strong></p>
<p>别人怎么知道你找的这个经纪人就是明星的经纪人？<strong>要是冒充怎么办？</strong></p>
<p>谁来证明呢？当然是明星本人亚！可以通过拿到<strong>明星本人的认证书</strong>来证明！</p>
<p><br></p>
<p>ok，上面讲到的内容就是代理模式的<strong>核心思想</strong>！</p>
<h3 id="2）现在我们讲讲具体的实现！"><a href="#2）现在我们讲讲具体的实现！" class="headerlink" title="2）现在我们讲讲具体的实现！"></a>2）现在我们讲讲具体的实现！</h3><p>在Java中，要想实现代理对象，同样的也需要满足上面的要求：</p>
<p><strong>1.代理类要能够伪装目标类</strong></p>
<p><br></p>
<p>那么如何伪装呢？多态！</p>
<p>什么是多态？这里不想去引用一些官方术语，实属太难记了，不容理解。</p>
<p><strong>我们直接上代码：</strong></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Father</span></span>&#123;
    
&#125;
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Son</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Father</span></span>&#123;
    
&#125;  
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String [] args)</span></span>&#123;
    <span class="hljs-comment">//父类的引用指向自己</span>
    Father father=<span class="hljs-keyword">new</span> Father()
    <span class="hljs-comment">//父类的引用指向子类</span>
    Father son=<span class="hljs-keyword">new</span> Son();
&#125;</code></pre></div>
<p><strong>Father father=new Son();</strong></p>
<p>这种代码估计大部分人都写过，但是有考虑过为什么可以这么写吗？</p>
<p>这里实际上就是<strong>父类的引用指向子类！</strong></p>
<p><strong>也就是说一个对象的引用变量，只有在运行期间才能够真正确定自己指向的是哪一个对象！</strong></p>
<p><strong>可能是其他对象！也有可能指向的是自己！从而导致一个引用可以有多种不同的形态！</strong></p>
<p><strong><code>这就是多态！</code></strong></p>
<p><br></p>
<p><strong>实际上，不仅仅是继承，其实接口的实现也是一种父子类的关系，所以同样也会有多态的产生。</strong></p>
<p><strong>ok，仔细看上面的代码，是不是已经帮我们实现了伪装了？</strong></p>
<p><strong>所以，要想实现代理，可以利用多态来实现伪装！</strong></p>
<p><strong>说白了，就是可以利用接口和继承来实现！</strong></p>
<h2 id="静态代理"><a href="#静态代理" class="headerlink" title="静态代理"></a>静态代理</h2><p>静态代理，就和名字一样，静态的呗，什么叫静态？<strong>写死了呗</strong>！</p>
<p>还是上面的场景，我们如何给打印业务实现一个静态代理？</p>
<p><br></p>
<p><strong><code>首先我们利用接口的实现来完成代理。</code></strong></p>
<p><br></p>
<p><strong>先写一个公共的接口类：</strong></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">PrintInterFace</span> </span>&#123;

    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">print</span><span class="hljs-params">(String name)</span></span>;
&#125;</code></pre></div>
<p><strong>实现它：</strong></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PrintName</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">PrintInterFace</span> </span>&#123;
    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">print</span><span class="hljs-params">(String name)</span> </span>&#123;
        System.out.println(<span class="hljs-string">"name="</span> + name);
    &#125;
&#125;</code></pre></div>
<p>然后我们写一个代理类，也去实现这个接口。</p>
<p>同时，为了能够实现目标类的方法，我们只需要将目标类也传给代理类。</p>
<p>让代理类做了一些事情之后，在调用目标类，从而实现代理！</p>
<p><br></p>
<p><strong>代理类如下：</strong></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PrintStaticProxy</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">PrintInterFace</span> </span>&#123;
    <span class="hljs-comment">/**</span>
<span class="hljs-comment">     * 被代理对象，打印名字对象</span>
<span class="hljs-comment">     */</span>
    <span class="hljs-keyword">private</span> PrintName printName;
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">PrintStaticProxy</span><span class="hljs-params">(PrintInterFace printName)</span> </span>&#123;
        <span class="hljs-comment">//只代理这个打印名字对象</span>
        <span class="hljs-keyword">if</span> (printName.getClass() == PrintName<span class="hljs-class">.<span class="hljs-keyword">class</span>) </span>&#123;
            <span class="hljs-keyword">this</span>.printName = (PrintName) printName;
        &#125;
    &#125;

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">print</span><span class="hljs-params">(String name)</span> </span>&#123;
        <span class="hljs-comment">//1.执行代理方法</span>
        printName.print(name);

        <span class="hljs-comment">//2.在正式调用print方法之后调用增强方法</span>
        otherAction(name);
    &#125;

    <span class="hljs-comment">/**</span>
<span class="hljs-comment">     * 添加的其他增强方法</span>
<span class="hljs-comment">     */</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">otherAction</span><span class="hljs-params">(String name)</span> </span>&#123;
        System.out.println(<span class="hljs-string">"亲亲"</span> + name);
    &#125;
&#125;</code></pre></div>
<p><br></p>
<p><strong>ok，我们测试一下：</strong></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MainTest</span> </span>&#123;
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>&#123;
        String name = <span class="hljs-string">"甜甜"</span>;
        System.out.println(<span class="hljs-string">"///////////////静态代理测试开始////////////"</span>);
        <span class="hljs-comment">//1.生成代理对象</span>
        PrintInterFace proxy = <span class="hljs-keyword">new</span> PrintStaticProxy(<span class="hljs-keyword">new</span> PrintName());

        <span class="hljs-comment">//2.代理对象执行方法</span>
        proxy.print(name);
    &#125;
&#125;</code></pre></div>
<p><br></p>
<p><strong>测试结果：</strong></p>
<p><img src="https://bins-pic.oss-cn-shanghai.aliyuncs.com/mypic/image-20200718171616363.png" srcset="/binblog/img/loading.gif" alt="image-20200718171616363"></p>
<p><br></p>
<p>静态代理不适合处理很复杂的大型业务，因为可扩展性非常的差。</p>
<p>一个静态代理类基本只能实现一个接口，那就只能代理这一个接口，非常的不灵活！</p>
<p>这就是为什么还出现<strong>动态代理！</strong></p>
<h2 id="动态代理"><a href="#动态代理" class="headerlink" title="动态代理"></a>动态代理</h2><p><strong>要说动态代理和静态的最大区别，我们要想生成一个代理对象不需要像之前那样写死了！</strong></p>
<p><strong>理想的情况下应该是根据具体情况自动生成一个目标的代理对象！</strong></p>
<p><br></p>
<p><strong>那要如何才能实现这种动态定制呢？</strong></p>
<p><strong>有两种方法：</strong></p>
<p><strong>1.使用JDK自带的代理工具：JDK代理包</strong></p>
<p><strong>2.使用CGLIB自带的代理工具：CGLIB代理包</strong></p>
<p><br></p>
<h3 id="1）JDK动态代理"><a href="#1）JDK动态代理" class="headerlink" title="1）JDK动态代理"></a>1）JDK动态代理</h3><p>动态定制？说白了就是造一个对象出来！</p>
<p>这个对象拥有了像静态代理一样功能的对象！</p>
<p>如何造？造，那就是具体情况生成一个新的对象咯。</p>
<p>生成一个<strong>对象</strong>要干哪些事情？：</p>
<p><strong>1.写好.java文件</strong></p>
<p><strong>2.编译.java文件，生成.class字节码文件</strong></p>
<p><strong>3.加载字节码文件，初始化对象。</strong></p>
<p><br></p>
<p>写？谁来写亚？不是动态吗？还要写代码？</p>
<p>no no no，既然是动态，那就要交给别人去生成。</p>
<p>那么如何在代码中在写一个java文件呢？</p>
<p>你想呀，java文件本质上不就是一些代码吗，代码本质上不就是字符串吗？</p>
<p>所以我们只要进行字符串的拼接就行了亚！</p>
<p>具体如何通过字符串的拼接新生成一个java文件可以参考下面提到的文章。</p>
<p>这里不做描述。</p>
<p><br></p>
<p>这里之所以提到动态生成，是因为JDK代理的底层就是这么干的！</p>
<p>它会要求你传一个目标对象和一个加强方法。</p>
<p>然后就可以给你返回一个代理对象了。</p>
<p><strong>具体代码：</strong></p>
<p><strong>加强方法的实现：</strong></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyInvocationHandler</span>&lt;<span class="hljs-title">T</span>&gt; <span class="hljs-keyword">implements</span> <span class="hljs-title">InvocationHandler</span> </span>&#123;
    <span class="hljs-comment">/**</span>
<span class="hljs-comment">     * 被代理对象</span>
<span class="hljs-comment">     */</span>
    <span class="hljs-keyword">private</span> T targetObject;
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">MyInvocationHandler</span><span class="hljs-params">(T targetObject)</span> </span>&#123;
        <span class="hljs-keyword">this</span>.targetObject = targetObject;
    &#125;

    <span class="hljs-comment">/**</span>
<span class="hljs-comment">     * 重写方法</span>
<span class="hljs-comment">     *</span>
<span class="hljs-comment">     * <span class="hljs-doctag">@param</span> proxy  动态代理对象</span>
<span class="hljs-comment">     * <span class="hljs-doctag">@param</span> method 正在被用户直接调用的接口中的方法</span>
<span class="hljs-comment">     * <span class="hljs-doctag">@param</span> args   对应方法中的参数</span>
<span class="hljs-comment">     * <span class="hljs-doctag">@return</span> 返回被代理对象中被调用方法的结果</span>
<span class="hljs-comment">     */</span>
    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> Object <span class="hljs-title">invoke</span><span class="hljs-params">(Object proxy, Method method, Object[] args)</span> <span class="hljs-keyword">throws</span> Throwable </span>&#123;
        <span class="hljs-comment">//代理对象来执行被代理对象中的方法</span>
        Object result = method.invoke(targetObject, args);

        <span class="hljs-comment">//执行增强方法</span>
        otherAction((String) args[<span class="hljs-number">0</span>]);

        <span class="hljs-comment">//返回被代理对象中被调用方法的结果</span>
        <span class="hljs-keyword">return</span> result;
    &#125;

    <span class="hljs-comment">/**</span>
<span class="hljs-comment">     * 添加的其他增强方法</span>
<span class="hljs-comment">     */</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">otherAction</span><span class="hljs-params">(String name)</span> </span>&#123;
        System.out.println(<span class="hljs-string">"亲亲"</span> + name);
    &#125;
&#125;</code></pre></div>
<p><br></p>
<p><strong>jdk代理工具类：</strong></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyJDKProxy</span> </span>&#123;
    <span class="hljs-comment">/**</span>
<span class="hljs-comment">     * 构造自己的代理类</span>
<span class="hljs-comment">     *</span>
<span class="hljs-comment">     * <span class="hljs-doctag">@param</span> loader     被代理类的类加载器</span>
<span class="hljs-comment">     * <span class="hljs-doctag">@param</span> interfaces 被代理类本身的Class对象</span>
<span class="hljs-comment">     * <span class="hljs-doctag">@return</span> 包装好的代理对象</span>
<span class="hljs-comment">     */</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> Object <span class="hljs-title">createProxy</span><span class="hljs-params">(ClassLoader loader,</span></span>
<span class="hljs-function"><span class="hljs-params">                                     Class&lt;?&gt;[] interfaces, InvocationHandler invocationHandler)</span> </span>&#123;
        <span class="hljs-comment">//构造代理对象的关键代码</span>
        <span class="hljs-keyword">return</span> Proxy.newProxyInstance(loader, interfaces, invocationHandler);
    &#125;
&#125;</code></pre></div>
<p><strong>测试代码：</strong></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MainTest</span> </span>&#123;
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>&#123;
        String name = <span class="hljs-string">"甜甜"</span>;
        System.out.println(<span class="hljs-string">"///////////////JDK代理测试开始////////////"</span>);
       <span class="hljs-comment">//1.根据被代理对象和调用执行器来创建一个代理对象</span>
        PrintInterFace proxy = (PrintInterFace) MyJDKProxy.createProxy(PrintInterFace<span class="hljs-class">.<span class="hljs-keyword">class</span>.<span class="hljs-title">getClassLoader</span>(),</span>
                new Class&lt;?&gt;[]&#123;PrintInterFace.class&#125;, new MyInvocationHandler(new PrintName()));
        
        
        <span class="hljs-comment">//2.代理对象执行方法</span>
        proxy.print(name);
    &#125;
&#125;</code></pre></div>
<p><strong>测试结果：</strong></p>
<p><img src="https://bins-pic.oss-cn-shanghai.aliyuncs.com/mypic/image-20200718173708730.png" srcset="/binblog/img/loading.gif" alt="image-20200718173708730"></p>
<p><strong>这里有一个问题，为什么jdk必须要使用要求只能代理那些有接口的类？</strong></p>
<p>你之前不是说还可以通过继承吗？继承的话就不用写接口了亚！</p>
<p>ok，是的，确实是这样子的。</p>
<p>但是，为了看的更明白代理对象的内容，我们将生成的代理对象的字节码文件输出到文件中：</p>
<p><strong>测试代码：</strong></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MainTest</span> </span>&#123;
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>&#123;
        String name = <span class="hljs-string">"甜甜"</span>;
        System.out.println(<span class="hljs-string">"///////////////JDK代理测试开始////////////"</span>);
       <span class="hljs-comment">//1.根据被代理对象和调用执行器来创建一个代理对象</span>
        PrintInterFace proxy = (PrintInterFace) MyJDKProxy.createProxy(PrintInterFace<span class="hljs-class">.<span class="hljs-keyword">class</span>.<span class="hljs-title">getClassLoader</span>(),</span>
                new Class&lt;?&gt;[]&#123;PrintInterFace.class&#125;, new MyInvocationHandler(new PrintName()));
        
        <span class="hljs-comment">//生成代理对象的字节码文件</span>
        PrintName printName = <span class="hljs-keyword">new</span> PrintName();
        Class&lt;? extends PrintName&gt; clazz = printName.getClass();
        <span class="hljs-keyword">try</span> &#123;
            <span class="hljs-keyword">byte</span>[] bytes = ProxyGenerator.generateProxyClass(<span class="hljs-string">"proxy"</span>, clazz.getInterfaces());
            File file = <span class="hljs-keyword">new</span> File(<span class="hljs-string">"C:\\Users\\Bing\\Desktop\\proxy.class"</span>);
            FileOutputStream outputStream = <span class="hljs-keyword">new</span> FileOutputStream(file);
            outputStream.write(bytes);
        &#125; <span class="hljs-keyword">catch</span> (IOException e) &#123;
            e.printStackTrace();
        &#125;
        
        <span class="hljs-comment">//2.代理对象执行方法</span>
        proxy.print(name);
    &#125;
&#125;</code></pre></div>
<p><strong>然后用IDEA打开它：</strong></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">final</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">proxy</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Proxy</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">PrintInterFace</span> </span>&#123;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> Method m1;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> Method m2;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> Method m0;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> Method m3;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">proxy</span><span class="hljs-params">(InvocationHandler var1)</span> <span class="hljs-keyword">throws</span>  </span>&#123;
        <span class="hljs-keyword">super</span>(var1);
    &#125;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">boolean</span> <span class="hljs-title">equals</span><span class="hljs-params">(Object var1)</span> <span class="hljs-keyword">throws</span>  </span>&#123;
        <span class="hljs-keyword">try</span> &#123;
            <span class="hljs-keyword">return</span> (Boolean)<span class="hljs-keyword">super</span>.h.invoke(<span class="hljs-keyword">this</span>, m1, <span class="hljs-keyword">new</span> Object[]&#123;var1&#125;);
        &#125; <span class="hljs-keyword">catch</span> (RuntimeException | Error var3) &#123;
            <span class="hljs-keyword">throw</span> var3;
        &#125; <span class="hljs-keyword">catch</span> (Throwable var4) &#123;
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> UndeclaredThrowableException(var4);
        &#125;
    &#125;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">final</span> String <span class="hljs-title">toString</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span>  </span>&#123;
        <span class="hljs-keyword">try</span> &#123;
            <span class="hljs-keyword">return</span> (String)<span class="hljs-keyword">super</span>.h.invoke(<span class="hljs-keyword">this</span>, m2, (Object[])<span class="hljs-keyword">null</span>);
        &#125; <span class="hljs-keyword">catch</span> (RuntimeException | Error var2) &#123;
            <span class="hljs-keyword">throw</span> var2;
        &#125; <span class="hljs-keyword">catch</span> (Throwable var3) &#123;
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> UndeclaredThrowableException(var3);
        &#125;
    &#125;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> <span class="hljs-title">hashCode</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span>  </span>&#123;
        <span class="hljs-keyword">try</span> &#123;
            <span class="hljs-keyword">return</span> (Integer)<span class="hljs-keyword">super</span>.h.invoke(<span class="hljs-keyword">this</span>, m0, (Object[])<span class="hljs-keyword">null</span>);
        &#125; <span class="hljs-keyword">catch</span> (RuntimeException | Error var2) &#123;
            <span class="hljs-keyword">throw</span> var2;
        &#125; <span class="hljs-keyword">catch</span> (Throwable var3) &#123;
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> UndeclaredThrowableException(var3);
        &#125;
    &#125;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">void</span> <span class="hljs-title">print</span><span class="hljs-params">(String var1)</span> <span class="hljs-keyword">throws</span>  </span>&#123;
        <span class="hljs-keyword">try</span> &#123;
            <span class="hljs-keyword">super</span>.h.invoke(<span class="hljs-keyword">this</span>, m3, <span class="hljs-keyword">new</span> Object[]&#123;var1&#125;);
        &#125; <span class="hljs-keyword">catch</span> (RuntimeException | Error var3) &#123;
            <span class="hljs-keyword">throw</span> var3;
        &#125; <span class="hljs-keyword">catch</span> (Throwable var4) &#123;
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> UndeclaredThrowableException(var4);
        &#125;
    &#125;

    <span class="hljs-keyword">static</span> &#123;
        <span class="hljs-keyword">try</span> &#123;
            m1 = Class.forName(<span class="hljs-string">"java.lang.Object"</span>).getMethod(<span class="hljs-string">"equals"</span>, Class.forName(<span class="hljs-string">"java.lang.Object"</span>));
            m2 = Class.forName(<span class="hljs-string">"java.lang.Object"</span>).getMethod(<span class="hljs-string">"toString"</span>);
            m0 = Class.forName(<span class="hljs-string">"java.lang.Object"</span>).getMethod(<span class="hljs-string">"hashCode"</span>);
            m3 = Class.forName(<span class="hljs-string">"com.bins.desighpattern.proxy.PrintInterFace"</span>).getMethod(<span class="hljs-string">"print"</span>, Class.forName(<span class="hljs-string">"java.lang.String"</span>));
        &#125; <span class="hljs-keyword">catch</span> (NoSuchMethodException var2) &#123;
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> NoSuchMethodError(var2.getMessage());
        &#125; <span class="hljs-keyword">catch</span> (ClassNotFoundException var3) &#123;
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> NoClassDefFoundError(var3.getMessage());
        &#125;
    &#125;
&#125;</code></pre></div>
<p>可以看到的是，这个代理默认是<strong>继承</strong>了一个叫做<strong>Proxy</strong>的对象，然后才是<strong>实现了</strong>我们的接口。</p>
<p>也就是说，要想使用jdk代理，它的内部会帮我们继承了一个对象。</p>
<p>因为Java中是单继承的，所以只能在实现另一个接口才能实现代理的功能！</p>
<p>不仅如此，大家想一下，假设继承成立的话。</p>
<p>那么代理类中是不是还会拥有代理对象中的所有属性？（private除外）</p>
<p>但是我们的代理类不过就是帮目标对象做了一些其他的事情而已，用的着全继承吗？</p>
<p>那这样多占内存亚！其他的属性也用不到！</p>
<h3 id="2）CGLIB动态代理"><a href="#2）CGLIB动态代理" class="headerlink" title="2）CGLIB动态代理"></a>2）CGLIB动态代理</h3><p>如果说JDK动态代理是通过一个实现目标对象的父类接口来实现的。</p>
<p>那么CGLIB就是通过直接继承目标对象来实现的！</p>
<p>也就是说，如果实在没有父类接口，那么通过使用CGLIB同样也可以实现动态代理。</p>
<p>和JDK不同的是，CGLIB底层是通过直接生成字节码文件来继承目标对象。</p>
<p>并同时实现加强方法！</p>
<p><br></p>
<p>要想要使用<strong>CGLIB</strong>，需要导入对应的依赖包：</p>
<div class="hljs"><pre><code class="hljs xml"><span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>cglib<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>cglib<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>2.2.2<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span></code></pre></div>
<p><br></p>
<p>因为不需要实现接口，所以接口就不用，直接用上面提到的实现类就行：</p>
<p><br></p>
<p>同样的，我们也要实现自己的<strong>增强方法</strong>：</p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyMethodInterceptor</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">MethodInterceptor</span> </span>&#123;
    <span class="hljs-comment">/**</span>
<span class="hljs-comment">     * 方法拦截器</span>
<span class="hljs-comment">     *</span>
<span class="hljs-comment">     * <span class="hljs-doctag">@param</span> o           代理类</span>
<span class="hljs-comment">     * <span class="hljs-doctag">@param</span> method      被代理类调用的方法</span>
<span class="hljs-comment">     * <span class="hljs-doctag">@param</span> objects     方法参数集合</span>
<span class="hljs-comment">     * <span class="hljs-doctag">@param</span> methodProxy 代理方法</span>
<span class="hljs-comment">     * <span class="hljs-doctag">@return</span> 被代理类执行的方法的返回结果</span>
<span class="hljs-comment">     * <span class="hljs-doctag">@throws</span> Throwable</span>
<span class="hljs-comment">     */</span>
    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> Object <span class="hljs-title">intercept</span><span class="hljs-params">(Object o, Method method, Object[] objects, MethodProxy methodProxy)</span> <span class="hljs-keyword">throws</span> Throwable </span>&#123;
        <span class="hljs-comment">//调用父类中的方法</span>
        Object result = methodProxy.invokeSuper(o, objects);
        <span class="hljs-comment">//执行增强方法</span>
        otherAction(objects);
        <span class="hljs-keyword">return</span> result;
    &#125;

    <span class="hljs-comment">/**</span>
<span class="hljs-comment">     * 添加的其他增强方法</span>
<span class="hljs-comment">     */</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">otherAction</span><span class="hljs-params">(Object[] objects)</span> </span>&#123;
        <span class="hljs-keyword">for</span> (Object o : objects) &#123;
            System.out.println(<span class="hljs-string">"亲亲"</span> + o.toString());
        &#125;
    &#125;
&#125;</code></pre></div>
<p><br></p>
<p><strong>同样也可以写一个工具类：</strong></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyCGLIBProxy</span> </span>&#123;
    <span class="hljs-comment">/**</span>
<span class="hljs-comment">     * 根据一个类型产生代理类，此方法不要求一定放在MethodInterceptor中</span>
<span class="hljs-comment">     *</span>
<span class="hljs-comment">     * <span class="hljs-doctag">@param</span> clazz 被代理类的Class对象</span>
<span class="hljs-comment">     * <span class="hljs-doctag">@return</span> 代理对象</span>
<span class="hljs-comment">     */</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> Object <span class="hljs-title">createProxy</span><span class="hljs-params">(Class&lt;?&gt; clazz, MethodInterceptor interceptor)</span> </span>&#123;
        Enhancer enhancer = <span class="hljs-keyword">new</span> Enhancer();
        enhancer.setSuperclass(clazz);
        <span class="hljs-comment">//通过自定义方法拦截器实现加强方法</span>
        enhancer.setCallback(interceptor);
        <span class="hljs-keyword">return</span> enhancer.create();
    &#125;
&#125;</code></pre></div>
<p><br></p>
<p><strong>测试代码：</strong></p>
<div class="hljs"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MainTest</span> </span>&#123;
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>&#123;
        String name = <span class="hljs-string">"甜甜"</span>;
        System.out.println(<span class="hljs-string">"///////////////CGLIB代理测试开始////////////"</span>);
        <span class="hljs-comment">//1.根据代理类以及被代理类动态创建代理对象</span>
        PrintName printName = (PrintName) MyCGLIBProxy.createProxy(PrintName<span class="hljs-class">.<span class="hljs-keyword">class</span>, <span class="hljs-title">new</span> <span class="hljs-title">MyMethodInterceptor</span>())</span>;

        <span class="hljs-comment">//2.被代理对象执行方法（实质上是代理对象执行的）</span>
        printName.print(name);
    &#125;
&#125;</code></pre></div>
<p><br></p>
<p><strong>测试结果：</strong></p>
<p><img src="https://bins-pic.oss-cn-shanghai.aliyuncs.com/mypic/image-20200718182016834.png" srcset="/binblog/img/loading.gif" alt="image-20200718182016834"></p>
<h3 id="3）JDK代理和CGLIB的优缺点"><a href="#3）JDK代理和CGLIB的优缺点" class="headerlink" title="3）JDK代理和CGLIB的优缺点"></a>3）JDK代理和CGLIB的优缺点</h3><p><strong>这里就简单说下性能的问题吧。</strong></p>
<p><strong>在jdk1.8之前，JDK动态代理和CGLIB动态代理的性能差距比较大。</strong></p>
<p><strong>一般来说JDK会慢10倍左右。</strong></p>
<p><strong>但是之后到了jdk1.8，对JDK动态代理进行了优化，现在的JDK和CGLIB性能都差不多。</strong></p>
<h2 id="最后"><a href="#最后" class="headerlink" title="最后"></a>最后</h2><p>啊，这篇文章写了半天，又肝到凌晨才写完。</p>
<p>总体的思路还是很清晰的。</p>
<p><strong>睡觉睡觉💤</strong></p>
<h2 id="参考"><a href="#参考" class="headerlink" title="参考"></a>参考</h2><p>1.<a href="https://mp.weixin.qq.com/s/TLhuQ6Eiqk5Js8NlRbaOZw" target="_blank" rel="noopener">https://mp.weixin.qq.com/s/TLhuQ6Eiqk5Js8NlRbaOZw</a></p>
<p>2.<a href="https://mp.weixin.qq.com/s/3NI_JsxT-MhxCZzXyu60zg" target="_blank" rel="noopener">https://mp.weixin.qq.com/s/3NI_JsxT-MhxCZzXyu60zg</a></p>

            </article>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                  <div class="post-meta mr-3">
                    <i class="iconfont icon-category"></i>
                    
                      <a class="hover-with-bg" href="/binblog/categories/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/">设计模式</a>
                    
                  </div>
                
                
              </div>
              
                <p class="note note-warning">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh" target="_blank" rel="nofollow noopener noopener">CC BY-SA 4.0 协议</a> ，转载请注明出处！</p>
              
              
                <div class="post-prevnext row">
                  <div class="post-prev col-6">
                    
                    
                      <a href="/binblog/2020/05/31/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F%E4%B9%8B%E7%AD%96%E7%95%A5%E6%A8%A1%E5%BC%8F/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">设计模式之策略模式</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </div>
                  <div class="post-next col-6">
                    
                    
                      <a href="/binblog/2020/05/31/%E7%BA%AF%E6%89%8B%E5%86%99LRU%E7%AE%97%E6%B3%95%EF%BC%81/">
                        <span class="hidden-mobile">纯手写LRU算法！</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </div>
                </div>
              
            </div>

            
              <!-- Comments -->
              <div class="comments" id="comments">
                
                
  <div id="vcomments"></div>
  <script defer src="https://cdn.staticfile.org/valine/1.4.14/Valine.min.js" ></script>

  <script type="text/javascript">
    var oldLoadVa = window.onload;
    window.onload = function () {
      oldLoadVa && oldLoadVa();

      new Valine({
        el: "#vcomments",
        app_id: "vsanVmkaurLHyq2Xey9odo5V-gzGzoHsz",
        app_key: "v2hMMe4Mzz3mqpy9jwd7qx8B",
        placeholder: "说点什么吧！",
        path: window.location.pathname,
        avatar: "retro",
        meta: ["nick","mail","link"],
        pageSize: "10",
        lang: "zh-CN",
        highlight: true,
        recordIP: false,
        serverURLs: "",
      });
    };
  </script>
  <noscript>Please enable JavaScript to view the <a href="https://valine.js.org" target="_blank" rel="nofollow noopener noopener">comments
      powered by Valine.</a></noscript>


              </div>
            
          </div>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div id="tocbot"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    
  </main>

  
    <a id="scroll-top-button" href="#" role="button">
      <i class="iconfont icon-arrowup" aria-hidden="true"></i>
    </a>
  

  
    <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
  

  

  

  <footer class="mt-5">
  <div class="text-center py-3">
    <div>
      <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a>
      <i class="iconfont icon-love"></i>
      <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener">
        <span>Fluid</span></a>
    </div>
    
  <div class="statistics">
    
    

    
      
        <!-- LeanCloud 统计PV -->
        <span id="leancloud-site-pv-container" style="display: none">
            总访问量 
            <span id="leancloud-site-pv"></span>
             次
          </span>
      
      
        <!-- LeanCloud 统计UV -->
        <span id="leancloud-site-uv-container" style="display: none">
            总访客数 
            <span id="leancloud-site-uv"></span>
             人
          </span>
      

    
  </div>


    
  <!-- 备案信息 -->
  <div class="beian">
    <a href="http://beian.miit.gov.cn/" target="_blank"
       rel="nofollow noopener">京ICP证123456号</a>
    
      <a
        href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=12345678"
        rel="nofollow noopener"
        class="beian-police"
        target="_blank"
      >
        <span class="beian-police-sep">&nbsp;|&nbsp;</span>
        
          <img src="/binblog/img/police_beian.png" srcset="/binblog/img/loading.gif" alt="police-icon" />
        
        <span>京公网安备12345678号</span>
      </a>
     
  </div>


    
  </div>
</footer>

<!-- SCRIPTS -->
<script  src="https://cdn.staticfile.org/jquery/3.4.1/jquery.min.js" ></script>
<script  src="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/js/bootstrap.min.js" ></script>
<script  src="/binblog/js/debouncer.js" ></script>
<script  src="/binblog/js/main.js" ></script>

<!-- Plugins -->


  
    <script  src="/binblog/js/lazyload.js" ></script>
  



  <script defer src="https://cdn.staticfile.org/clipboard.js/2.0.6/clipboard.min.js" ></script>
  <script  src="/binblog/js/clipboard-use.js" ></script>



  <script defer>
  (function () {
    // 查询存储的记录
    function getRecord(Counter, target) {
      return new Promise(function (resolve, reject) {
        Counter('get', '/classes/Counter?where=' + encodeURIComponent(JSON.stringify({target})))
          .then(resp => resp.json())
          .then(({results, code, error}) => {
            if (code === 401) {
              throw error;
            }
            if (results && results.length > 0) {
              var record = results[0];
              resolve(record);
            } else {
              Counter('post', '/classes/Counter', {target, time: 0})
                .then(resp => resp.json())
                .then((record, error) => {
                  if (error) {
                    throw error;
                  }
                  resolve(record);
                }).catch(error => {
                console.error('Failed to create', error);
                reject(error);
              });
            }
          }).catch((error) => {
          console.error('LeanCloud Counter Error:', error);
          reject(error);
        });
      })
    }

    // 发起自增请求
    function increment(Counter, incrArr) {
      return new Promise(function (resolve, reject) {
        Counter('post', '/batch', {
          "requests": incrArr
        }).then((res) => {
          res = res.json();
          if (res.error) {
            throw res.error;
          }
          resolve(res);
        }).catch((error) => {
          console.error('Failed to save visitor count', error);
          reject(error);
        });
      });
    }

    // 构建自增请求体
    function buildIncrement(objectId) {
      return {
        "method": "PUT",
        "path": `/1.1/classes/Counter/${ objectId }`,
        "body": {
          "time": {
            '__op': 'Increment',
            'amount': 1
          }
        }
      }
    }

    // 校验是否为有效的 UV
    function validUV() {
      var key = 'LeanCloud_UV_Flag';
      var flag = localStorage.getItem(key);
      if (flag) {
        // 距离标记小于 24 小时则不计为 UV
        if (new Date().getTime() - parseInt(flag) <= 86400000) {
          return false;
        }
      }
      localStorage.setItem(key, new Date().getTime().toString());
      return true;
    }

    function addCount(Counter) {
      var enableIncr = 'true' === 'true' && window.location.hostname !== 'localhost';
      var getterArr = [];
      var incrArr = [];

      // 请求 PV 并自增
      var pvCtn = document.querySelector('#leancloud-site-pv-container');
      if (pvCtn || enableIncr) {
        var pvGetter = getRecord(Counter, 'site-pv').then((record) => {
          incrArr.push(buildIncrement(record.objectId))
          var ele = document.querySelector('#leancloud-site-pv');
          if (ele) {
            ele.innerText = record.time + 1;
            if (pvCtn) {
              pvCtn.style.display = 'inline';
            }
          }
        });
        getterArr.push(pvGetter);
      }

      // 请求 UV 并自增
      var uvCtn = document.querySelector('#leancloud-site-uv-container');
      if (uvCtn || enableIncr) {
        var uvGetter = getRecord(Counter, 'site-uv').then((record) => {
          var vuv = validUV();
          vuv && incrArr.push(buildIncrement(record.objectId))
          var ele = document.querySelector('#leancloud-site-uv');
          if (ele) {
            ele.innerText = record.time + (vuv ? 1 : 0);
            if (uvCtn) {
              uvCtn.style.display = 'inline';
            }
          }
        });
        getterArr.push(uvGetter);
      }

      // 如果是文章，请求文章的浏览数，并自增
      if ('true' === 'true') {
        var viewCtn = document.querySelector('#leancloud-post-views-container');
        if (viewCtn || enableIncr) {
          var target = decodeURI('/binblog/2020/05/31/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F%E4%B9%8B%E4%BB%A3%E7%90%86%E6%A8%A1%E5%BC%8F/');
          var viewGetter = getRecord(Counter, target).then((record) => {
            incrArr.push(buildIncrement(record.objectId))
            if (viewCtn) {
              var ele = document.querySelector('#leancloud-post-views');
              if (ele) {
                ele.innerText = (record.time || 0) + 1;
                viewCtn.style.display = 'inline';
              }
            }
          });
          getterArr.push(viewGetter);
        }
      }

      // 如果启动计数自增，批量发起自增请求
      if (enableIncr) {
        Promise.all(getterArr).then(() => {
          incrArr.length > 0 && increment(Counter, incrArr);
        })
      }
    }

    var app_id = 'vsanVmkaurLHyq2Xey9odo5V-gzGzoHsz'
    var app_key = 'v2hMMe4Mzz3mqpy9jwd7qx8B'
    var server_url = ''

    function fetchData(api_server) {
      var Counter = (method, url, data) => {
        return fetch(`${ api_server }/1.1${ url }`, {
          method,
          headers: {
            'X-LC-Id': app_id,
            'X-LC-Key': app_key,
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(data)
        });
      };

      addCount(Counter);
    }

    var api_server = app_id.slice(-9) !== '-MdYXbMMI' ? server_url : `https://${ app_id.slice(0, 8).toLowerCase() }.api.lncldglobal.com`;

    if (api_server) {
      fetchData(api_server);
    } else {
      fetch('https://app-router.leancloud.cn/2/route?appId=' + app_id)
        .then(resp => resp.json())
        .then(({api_server}) => {
          fetchData('https://' + api_server);
        });
    }
  })();
</script>






  <script  src="https://cdn.staticfile.org/tocbot/4.11.1/tocbot.min.js" ></script>
  <script>
    $(document).ready(function () {
      var boardCtn = $('#board-ctn');
      var boardTop = boardCtn.offset().top;

      tocbot.init({
        tocSelector: '#tocbot',
        contentSelector: 'article.markdown-body',
        headingSelector: 'h1,h2,h3,h4,h5,h6',
        linkClass: 'tocbot-link',
        activeLinkClass: 'tocbot-active-link',
        listClass: 'tocbot-list',
        isCollapsedClass: 'tocbot-is-collapsed',
        collapsibleClass: 'tocbot-is-collapsible',
        collapseDepth: 0,
        scrollSmooth: true,
        headingsOffset: -boardTop
      });
      if ($('.toc-list-item').length > 0) {
        $('#toc').css('visibility', 'visible');
      }
    });
  </script>



  <script  src="https://cdn.staticfile.org/typed.js/2.0.11/typed.min.js" ></script>
  <script>
    var typed = new Typed('#subtitle', {
      strings: [
        '  ',
        "设计模式之代理模式&nbsp;",
      ],
      cursorChar: "_",
      typeSpeed: 70,
      loop: false,
    });
    typed.stop();
    $(document).ready(function () {
      $(".typed-cursor").addClass("h2");
      typed.start();
    });
  </script>



  <script  src="https://cdn.staticfile.org/anchor-js/4.2.2/anchor.min.js" ></script>
  <script>
    anchors.options = {
      placement: "right",
      visible: "hover",
      
    };
    var el = "h1,h2,h3,h4,h5,h6".split(",");
    var res = [];
    for (item of el) {
      res.push(".markdown-body > " + item)
    }
    anchors.add(res.join(", "))
  </script>



  <script  src="/binblog/js/local-search.js" ></script>
  <script>
    var path = "/binblog/local-search.xml";
    var inputArea = document.querySelector("#local-search-input");
    inputArea.onclick = function () {
      searchFunc(path, 'local-search-input', 'local-search-result');
      this.onclick = null
    }
  </script>



  <script  src="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.css" />

  <script>
    $('#post img:not(.no-zoom img, img[no-zoom]), img[zoom]').each(
      function () {
        var element = document.createElement('a');
        $(element).attr('data-fancybox', 'images');
        $(element).attr('href', $(this).attr('src'));
        $(this).wrap(element);
      }
    );
  </script>





  

  
    <!-- MathJax -->
    <script>
      MathJax = {
        tex: {
          inlineMath: [['$', '$'], ['\\(', '\\)']]
        },
        options: {
          renderActions: {
            findScript: [10, doc => {
              document.querySelectorAll('script[type^="math/tex"]').forEach(node => {
                const display = !!node.type.match(/; *mode=display/);
                const math = new doc.options.MathItem(node.textContent, doc.inputJax[0], display);
                const text = document.createTextNode('');
                node.parentNode.replaceChild(text, node);
                math.start = { node: text, delim: '', n: 0 };
                math.end = { node: text, delim: '', n: 0 };
                doc.math.push(math);
              });
            }, '', false],
            insertedScript: [200, () => {
              document.querySelectorAll('mjx-container').forEach(node => {
                let target = node.parentNode;
                if (target.nodeName.toLowerCase() === 'li') {
                  target.parentNode.classList.add('has-jax');
                }
              });
            }, '', false]
          }
        }
      };
    </script>

    <script async src="https://cdn.staticfile.org/mathjax/3.0.5/es5/tex-svg.js" ></script>

  













  

  

  

  

  

  





<script src="/binblog/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"model":{"jsonPath":"/binblog/live2dw/assets/koharu.model.json"},"display":{"position":"right","width":150,"height":300},"mobile":{"show":true},"log":false,"pluginJsPath":"lib/","pluginModelPath":"assets/","pluginRootPath":"live2dw/","tagMode":false});</script></body>
</html>
